package com.huanong.it.fooder.controller;

import com.huanong.it.fooder.dto.ProductDTO;
import com.huanong.it.fooder.response.ApiResponse; // 引入 ApiResponse
import com.huanong.it.fooder.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
// 在 ProductController.java 顶部添加
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@RestController
@CrossOrigin(origins = "http://localhost:5173") // 允许来自该源的请求

@RequestMapping("/api/product")
public class ProductController {

    // 添加以下两行（关键修复）
    private static final Logger log = LogManager.getLogger(ProductController.class);

    @Autowired
    private ProductService productService;

    // 创建新商品
    @PostMapping("/create")
    public ResponseEntity<ProductDTO> createProduct(@RequestBody ProductDTO productDTO) {
        ProductDTO createdProduct = productService.createProduct(productDTO);
        return ResponseEntity.ok(createdProduct);
    }

    // 获取商品详情
    @PostMapping("/get/{id}")
    public ResponseEntity<ProductDTO> getProductById(@PathVariable Long id) {
        ProductDTO productDTO = productService.getProductById(id);
        return ResponseEntity.ok(productDTO);
    }

    // 获取所有商品
    @PostMapping("/list")
    public ApiResponse<List<ProductDTO>> getAllProducts() {
        log.info("查询所有商品信息"); // ✅ 现在log对象已正确初始化
        List<ProductDTO> products = productService.getAllProducts();
        return ApiResponse.success("商品列表获取成功", products);
    }


    // 更新商品
    @PostMapping("/update/{id}")
    public ResponseEntity<ProductDTO> updateProduct(@PathVariable Long id, @RequestBody ProductDTO productDTO) {
        ProductDTO updatedProduct = productService.updateProduct(id, productDTO);
        return ResponseEntity.ok(updatedProduct);
    }

    // 删除商品
    @PostMapping("/delete/{id}")
    public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
        productService.deleteProduct(id);
        return ResponseEntity.noContent().build();
    }
}
